<?php

namespace common\traits;

/**
 * Description of Constants
 *
 * @author emhome
 */
trait GenerateUniqueNumber {

    public function generateUniqueNumber($attribute, $rules = [], $default = 0) {
        $rules['year'] = date('y') % 10;
        $rules['day'] = str_pad(date('z'), 3, 0, STR_PAD_LEFT);
        do {
            $micro = round((microtime(true) - strtotime('today')) * 1000);
            $rules['micro'] = str_pad($micro, 8, $default, STR_PAD_RIGHT);
            $code = strtoupper(implode($rules));
            $record = static::find()->where([$attribute => $code])->exists();
        } while ($record);
        return $code;
    }

    public function generateCheckBitChar($number, $append = false) {
        //加权因子
        $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3];
        //校验码对应值 
        $code = '10X98765432';
        $numbers = str_split($number);
        $sum = 0;
        foreach ($numbers as $key => $char) {
            if (!is_numeric($char)) {
                $char = base_convert($char, 32, 10);
            }
            $pos = $key % 10;
            $sum += $char * $factor[$pos];
        }
        $cb = substr($code, $sum % 11, 1);
        if ($append !== false) {
            return $number . $cb;
        }
        return $cb;
    }

}
